<?php

class PersistentLogin
{
	function PersistentLogin() {}
	
	public function checkRememberCookie()
	{
		# persistent login handling starts		
		$CI =& get_instance();

		# set a general cookie just to check if the user has enabled cookies in his browser
		# this cookie is not connected in any way with persistent login, but because it's just one line,
		# i didn't move it to its own hook
		$CI->load->helper('cookie');
		setcookie('tt.me', 1, time() + 63072000, '/', $CI->config->item('cookie_domain'), 0, true);
		
		# do not check and update remembered login cookie if user currenly has normal session and is logged in
		if( (int)$CI->session->userdata('user_id') > 0 ) return;
		
		$rememberMeCookie = get_cookie('usr');
		if($rememberMeCookie)
		{
			$CI->load->library('encrypt');

			# clear expired persistant cookies
			$sql = "DELETE FROM user_remember WHERE expire < NOW()";
			$CI->db->query($sql);

			$decryptedCookie = $CI->encrypt->decode($rememberMeCookie);
			$user_credentials = explode('-', $decryptedCookie);

			$email = $CI->db->escape($user_credentials[0]);
			$series = $CI->db->escape($user_credentials[1]);
			$token = $user_credentials[2];
			
			$sql = "SELECT * FROM user_remember WHERE email = $email AND series_identifier = $series";
			$query = $CI->db->query($sql);
			
			if($query->num_rows() > 0)
			{
				$result = $query->result();
				$userinfo = $result[0];

				if($userinfo->series_identifier == $user_credentials[1])
				{
					if($userinfo->token === $token)
					{
						# login ok, replace existing token
						$new_token = substr( md5(uniqid(rand(),true) . $email), 0, 16);
						$new_ecsaped_token = $CI->db->escape($new_token);
						$sql = "UPDATE user_remember 
								SET token = $new_ecsaped_token 
								WHERE email = $email AND series_identifier = $series";
						$CI->db->query($sql);
						
						$cookie = $CI->encrypt->encode( $user_credentials[0] . '-' . $user_credentials[1] . '-' . $new_token );
						setcookie('usr', $cookie, time() + THREE_MONTHS, '/', $CI->config->item('cookie_domain'), 0, true);
						
						$CI->session->set_userdata('user_id', $userinfo->user_id);
						$CI->session->set_userdata('email', $userinfo->email);
						
						# remember me token is stored in the session here, so when a user log out from the
						# app, the remembered token will be deleted from the database (full logout)
						$CI->session->set_userdata('token', $new_token);
						
						# get user timezone
						$sql = "SELECT timezone FROM user WHERE user_id = $userinfo->user_id";
						$query = $CI->db->query($sql);
						$timezone = $query->row()->timezone;
						
						$CI->session->set_userdata('tz', $timezone);
					}
					else
					{
						# theft of cookie is assumed, remove all remembered logins
						$sql = "DELETE FROM user_remember WHERE email = $email";
						$CI->db->query($sql);
					}
				}	
			}
		}		
	}
}